<template>
  <div class="ai-chat">
    <s-header :name="'Ai客服'"></s-header>
    <div class="chat-content">
      <div class="messages" ref="messagesBox">
        <div v-for="(msg, index) in messages" :key="index"
             :class="['message', msg.sender]">
          <div v-if="msg.type === 'text'" class="text-message">
            {{ msg.content }}
          </div>
          <div v-else-if="msg.type === 'product'" class="product-card">
            <img :src="msg.content.image" alt="商品图">
            <h4>{{ msg.content.title }}</h4>
            <p>¥{{ msg.content.price }}</p>
          </div>
        </div>
      </div>
      <div v-if="currentProduct" class="quick-send">
        <button @click="sendProductInfo">
          发送当前商品：{{ currentProduct.title }}
        </button>
      </div>
      <div class="input-area">
      <textarea
          v-model="inputMessage"
          placeholder="输入问题..."
          @keyup.enter="sendMessage"
      ></textarea>
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import sHeader from '@/components/SimpleHeader.vue'
import {showSuccessToast, showToast} from 'vant'
import {prefix} from '@/common/js/utils'
import {getDetail} from '@/service/good'
import {chat, getChatHistory, saveChatHistory} from '@/service/chat'

const route = useRoute()
const router = useRouter()
const messages = ref([])
const replying = ref(false)
const inputMessage = ref('')
const messagesBox = ref(null)
const currentProduct = ref(null)

// 初始化
onMounted(async () => {
  // 如果有商品ID，获取商品信息
  const productId = route.query.productId
  if (productId) {
    await getProductInfo(productId)
  }

  // 加载聊天记录
  await loadChatHistory()

  // 如果没有聊天记录，添加欢迎消息
  if (messages.value.length === 0) {
    messages.value.push({
      type: 'text',
      sender: 'ai',
      content: '您好！我是AI客服助手，请问有什么可以帮您？'
    })
  }
})

// 加载聊天记录
const loadChatHistory = async () => {
  try {
    const {data} = await getChatHistory()
    if (data && data.length > 0) {
      data.forEach((item) => {
            if (item.message) {
              const userMsg = {
                type: 'text',
                sender: 'user',
                content: item.message
              }
              messages.value.push(userMsg)
            }
            if (item.goodsId) {
              const productInfo = {
                type: 'product',
                sender: 'user',
                content: {
                  title: item.productInfo.goodsName,
                  price: item.productInfo.originalPrice,
                  image: "http://backend-api-01.newbee.ltd/" + item.productInfo.goodsCoverImg
                }
              }
              messages.value.push(productInfo)
            }
            const aiMsg = {
              type: 'text',
              sender: 'ai',
              content: item.response
            }
            messages.value.push(aiMsg)
          }
      )
      await nextTick()
      scrollToBottom()
    }
  } catch
      (error) {
    console.log('没有历史聊天记录')
  }
}


// 获取商品信息
const getProductInfo = async (productId) => {
  try {
    const {data} = await getDetail(productId)
    currentProduct.value = {
      id: data.goodsId,
      title: data.goodsName,
      price: data.sellingPrice,
      image: prefix(data.goodsCarouselList[0])
    }
  } catch (error) {
    showToast('获取商品信息失败')
  }
}

// 发送消息
const sendMessage = () => {
  if (replying.value) {
    showToast('正在回复中，请稍等...')
    return;
  }
  if (!inputMessage.value.trim()) return
  const msg = inputMessage.value
  // 添加用户消息
  messages.value.push({
    type: 'text',
    sender: 'user',
    content: inputMessage.value
  })

  // 清空输入框
  inputMessage.value = ''
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })

  const params = {
    message: msg
  }
  // 模拟AI回复
  replying.value = true
  chat(params).then((res) => {
    messages.value.push({
      type: 'text',
      sender: 'ai',
      content: res.message
    })
    replying.value = false
  })
  nextTick(() => {
    scrollToBottom()
  })
}

// 发送商品信息
const sendProductInfo = () => {
  if (replying.value) {
    showToast('正在回复中，请稍等...')
    return;
  }

  if (!currentProduct.value) return
  messages.value.push({
    type: 'product',
    sender: 'user',
    content: {
      title: currentProduct.value.title,
      price: currentProduct.value.price,
      image: currentProduct.value.image
    }
  })
  const params = {
    productId: currentProduct.value.id
  }
  if (inputMessage.value) {
    params.message = inputMessage.value
  }
  console.log('params', params)
  replying.value = true
  chat(params).then((res) => {
    messages.value.push({
      type: 'text',
      sender: 'ai',
      content: res.message
    })
    replying.value = false
  })
  nextTick(() => {
    scrollToBottom()
  })
}

// 滚动到底部
const scrollToBottom = () => {
  const container = messagesBox.value
  container.scrollTop = container.scrollHeight
}
</script>
<style scoped lang="less">
@import '../common/style/mixin';

.ai-chat {
  .chat-content {
    height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
  }

  .messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
  }

  .message {
    margin-bottom: 20px;
    max-width: 80%;

    &.user {
      margin-left: auto;
    }

    &.ai {
      margin-right: auto;
    }
  }

  .text-message {
    padding: 10px 15px;
    border-radius: 10px;
    background: #fff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .product-card {
    background: #fff;
    border-radius: 10px;
    padding: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);

    img {
      width: 100%;
      height: 200px;
      object-fit: cover;
      border-radius: 5px;
    }

    h4 {
      margin: 10px 0;
      font-size: 16px;
    }

    p {
      color: #ff6b6b;
      font-weight: bold;
    }
  }

  .quick-send {
    padding: 10px 20px;
    background: #fff;
    border-top: 1px solid #eee;

    button {
      width: 100%;
      padding: 10px;
      background: @primary;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;

      &:hover {
        background: #0056b3;
      }
    }
  }

  .input-area {
    padding: 15px;
    background: #fff;
    border-top: 1px solid #eee;
    display: flex;
    gap: 10px;

    textarea {
      flex: 1;
      height: 40px;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      resize: none;
    }

    button {
      padding: 0 20px;
      background: @primary;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;

      &:hover {
        background: #0056b3;
      }
    }
  }
}
</style>